In [9]:
import numpy as np
import pandas
import matplotlib.pyplot as plt
from PIL import Image
%matplotlib inline
In [10]:
IMAGE_PATH = '../dataset/image/pic2.jpg'
In [11]:
image = Image.open(IMAGE_PATH)
img_arr = np.array(image)
img_arr = img_arr.reshape((-1,3)).swapaxes(0,1)
In [349]:
# select the k
k = 10
left_img_arr = []
prev_img_arr = []
for i,one_layer in enumerate(img_arr.astype(np.float64)):
# convert one layer into one image
one_image = one_layer.reshape((image.height,image.width))
U,s,V = np.linalg.svd(one_image)
plt.figure(i)
plt.plot(range(len(s)),s)
# check it
S = np.zeros((U.shape[0],V.shape[0]))
_min = min(U.shape[0],V.shape[0])
S[:_min,:_min] = np.diag(s)
prev_img_arr.append(np.dot(U,np.dot(S,V)).reshape((1,-1)))
print(np.allclose(one_image,prev_img_arr[i].reshape((image.height,image.width))))
if(len(s)<10):
k = len(s)
singular_sum = s.sum()
print('%d'%k,'%d in all'%len(s), ' left,left rate is : %f',left_rate)
s = s[:k]
left_singular_sum = s.sum()
left_rate = float(left_singular_sum/singular_sum)
print('compressed image displayed here')
left_U = U[:,:k]
left_V = V[:k,:]
left_S = np.diag(s)
left_image = np.dot(left_U,np.dot(left_S,left_V))
left_layer = left_image.reshape((-1,1))
# left_layer = mean + left_layer
left_img_arr.append(left_layer)
In [350]:
# for left_img_arr
left_img_arr = np.array(left_img_arr).reshape(3,-1)
prev_img_arr = np.array(prev_img_arr).reshape(3,-1)
In [351]:
left_img_arr[left_img_arr<0]=0
left_img_arr[left_img_arr>255]=255
In [ ]:
print(np.allclose(img_arr,prev_img_arr))
In [353]:
prev_img_arr = prev_img_arr.astype(np.int64).astype(np.uint8)
left_img_arr =left_img_arr.astype(np.int64).astype(np.uint8)
In [354]:
print(prev_img_arr)
print(img_arr)
print(left_img_arr)
Out[354]:
In [357]:
print(np.allclose(img_arr,prev_img_arr))
In [358]:
left_image = Image.fromarray(left_img_arr.swapaxes(0,1).reshape((image.height,image.width,-1)),'RGB')
prev_image = Image.fromarray(prev_img_arr.swapaxes(0,1).reshape((image.height,image.width,-1)),'RGB')
In [359]:
Image.fromarray(img_arr.swapaxes(0,1).reshape((image.height,image.width,-1)),'RGB')
Out[359]:
In [360]:
prev_image
Out[360]:
In [361]:
left_image
Out[361]: